package com.example.weatherokhttpdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText etCity;
    private Button btnSend1, btnSend2;
    private TextView tvResponseData;
    private TextView tvWeatherInfo;
    private String strUrl;
    private StringBuilder weatherInfo;
    private MyHandler myHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etCity = (EditText) findViewById(R.id.et_city);
        btnSend1 = (Button) findViewById(R.id.btnSend1);
        btnSend2 = (Button) findViewById(R.id.btnSend2);
        tvResponseData = (TextView) findViewById(R.id.tvResponseData);
        tvWeatherInfo = (TextView) findViewById(R.id.tvWeatherInfo);
        btnSend1.setOnClickListener(this);
        btnSend2.setOnClickListener(this);
        myHandler = new MyHandler();
    }

    @Override
    public void onClick(View view) {
        StringBuilder urlBuilder=new StringBuilder("https://api.seniverse.com/v3/weather/now.json?");
        urlBuilder.append("key=SrvH71t8JeTOXNLJP&language=zh-Hans&unit=c&location=");
        urlBuilder.append(etCity.getText().toString());  //将文本框中的城市名称添加到url的参数中
        strUrl=urlBuilder.toString();             //获取strUrl字符串，用于创建request对象
        tvResponseData.setText("");   //清空显示收到的Json数据的文本框
        tvWeatherInfo.setText("");    //清空显示解析后的天气数据的文本框
        if (view == btnSend1) {       //发送request请求，以同步Response方式，等待返回Response数据
            sendRequestWithOkHttpSync();
        } else if (view == btnSend2) {//发送request请求，以异步Response方式，在回调方法中获取Response数据
            sendRequestWithOkHttpAsync();
        }
    }

    //发送http请求，获取同步Response响应
    private void sendRequestWithOkHttpSync() {
        new Thread(new Runnable() {                         //开启一个子线程
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//创建一个OkHttpClient对象实例
                    Request request = new Request.Builder().url(strUrl).build();//创建Request对象
                    Call call = client.newCall(request); //调用OKhttpClient对象的newCall方法创建Call对象
                    Response response = call.execute();  //调用Call对象的execute()方法获取Response对象
                    //从Response对象中获取接收的数据
                    String responseData = response.body().string();
                    System.out.println(responseData);     //在run窗口显示responseData
                    showResPonse(responseData);           //显示原始数据和解析后的数据
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //发送请求，获取异步Response响应
    private void sendRequestWithOkHttpAsync() {
        OkHttpClient client = new OkHttpClient();     //创建一个OkhttpClient对象实例
        Request request = new Request.Builder().url(strUrl).build();  //创建Request对象
        Call call = client.newCall(request);         //使用OKHttpClient对象的newCall()方法创建Call对象
        //开启异步线程访问网络
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }

            //接收数据完成后执行的回调方法
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //从Response对象中获取接收的数据
                String responseData = response.body().string();
                System.out.println(responseData);         //在run窗口显示responseData
                Message msg = myHandler.obtainMessage();
                msg.what = 1;
                msg.obj = responseData;
                myHandler.sendMessage(msg);
            }
        });
    }

    //解析接收到的responseData数据,数据格式如下：
    /*
     *  {"results":[{"location":{"id":"WWKCX8PB3YE6","name":"日照","country":"CN","path":"日照,日照,山东,中国",
     * "timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"now":{"text":"晴","code":"1","temperature":"8"},
     * "last_update":"2021-12-02T18:11:31+08:00"}]}
     *
     * */
    private void parseJSONWithJSONObject(String jsonData) {//用JSONObect解析JSON数据
        try {
            JSONObject jsonObject = new JSONObject(jsonData);         //解析最外层的JsonData得到一个Json对象
            JSONArray results = jsonObject.getJSONArray("results");   //得到键为results的JSONArray
            JSONObject location = results.getJSONObject(0).getJSONObject("location");//得到键值为location的JSONObject
            JSONObject now = results.getJSONObject(0).getJSONObject("now"); //得到键值为"now"的JSONObject
            String last_update = results.getJSONObject(0).getString("last_update");//得到last_update的值
            //构建用于显示天气信息的字符串weatherInfo
            weatherInfo = new StringBuilder("results：");
            weatherInfo.append("\n    location:\n        name：" + location.getString("name"));  //城市名称
            weatherInfo.append("\n        country：" + location.getString("country"));      //国家代号
            weatherInfo.append("\n        path：" + location.getString("path"));            //区域组织结构
            weatherInfo.append("\n    now：\n        text:" + now.getString("text"));       //天气
            weatherInfo.append("\n        code：" + now.getString("code"));                 //天气编码
            weatherInfo.append("\n        temperature：" + now.getString("temperature"));   //气温
            weatherInfo.append("\n    last_update：" + last_update);                        //天气预报发布时间
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //获取同步响应后调用的方法，使用了runOnUiThread()方法，在UI线程中刷新界面
    private void showResPonse(final String response) {
        runOnUiThread(new Runnable() {//切换到主线程,ui界面的更改不能出现在子线程,否则app会崩溃
            @Override
            public void run() {
                tvResponseData.setText(response);
                parseJSONWithJSONObject(response);
                tvWeatherInfo.setText(weatherInfo.toString());
            }
        });
    }

    //获取异步响应后调用的方法，使用了Handler类的handleMessage()方法刷新UI界面
    class MyHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                parseJSONWithJSONObject(msg.obj.toString());
                tvResponseData.setText(msg.obj.toString());
                tvWeatherInfo.setText(weatherInfo.toString());
            }
        }
    }
}
